
package cnhy.salary.controller;

import cn.hutool.core.date.DateUtil;
import cnhy.salary.domain.RunDataRecord;
import cnhy.salary.domain.dto.EmployeeMonthlyWageDto;
import cnhy.salary.mapper.SalaryMapper;
import cnhy.salary.service.WageSvc;
import com.easy.query.core.api.dynamic.sort.ObjectSort;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.security.access.prepost.PreAuthorize;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
import java.util.*;
import lombok.*;
import com.ruoyi.common.core.page.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import cnhy.salary.domain.MonthlyWage;
//import cnhy.salary.service.MonthlyWageService;
import ling.common.*;
import ling.common.domain.*;

 /** 月工资 控制层
 * @author : He-LiangLiang@Outlook.com
 * @date : 2025-5-26
 */
@Api(tags = "月工资 功能接口")
@RestController
@RequestMapping("/salary/MonthlyWage")
public class MonthlyWageController extends EQueryController<MonthlyWage>{
    

    
    @ApiOperation("详情")
    @PreAuthorize("@ps.any(@pay.monthlyWage.query)")
    @GetMapping(value = "/{id}")
    public Result<MonthlyWage> getInfo(@PathVariable("id") Long id)
    {
       return super.getInfo(id);
    }
    
    @ApiOperation("分页列表")
    @PreAuthorize("@ps.any(@pay.monthlyWage.list)")
    @GetMapping("list")
    public ResultRows<MonthlyWage> list(MonthlyWage dto, PageDomain pageRequest) {


        return queryPage(dto,pageRequest);
    }

     @Override
     protected ResultRows<MonthlyWage> queryPage(Serializable whereObj, PageDomain pageRequest) {

         var dto = (MonthlyWage) whereObj;
         pageRequest = gainPageDomain(pageRequest);
         var pitem = queryHelper.query().queryable(MonthlyWage.class)
                 .whereObject(whereObj != null, whereObj)
                 .where(dto.getTime() != null,
                         p -> p.rangeClosedOpen(MonthlyWage::getTime, DateUtil.beginOfMonth(dto.getTime()), DateUtil.endOfMonth(dto.getTime())));
         if (pageRequest instanceof ObjectSort)
             pitem.orderByObject((ObjectSort) pageRequest);
         var pData = pitem.orderBy(p -> p.column(MonthlyWage::getOrderNum), true)
                .orderByDesc(p -> p.column(MonthlyWage::getId))
                .toPageResult(pageRequest.getPageNum(), pageRequest.getPageSize());

         return toResultRows(pData);
     }

     @ApiOperation("新增")
    @PreAuthorize("@ps.any(@pay.monthlyWage.add)")
    @Log(title = "月工资", businessType = BusinessType.INSERT)
    @PostMapping
    public Result add(@Validated @RequestBody MonthlyWage entity){
       return super.add(entity);
    }
    
    @ApiOperation("删除")
    @PreAuthorize("@ps.any(@pay.monthlyWage.remove)")
    @Log(title = "月工资", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public Result remove(@PathVariable("ids") Long[] ids){
        return super.remove(Arrays.stream(ids).toArray());
    }
    
    @ApiOperation("编辑")
    @PreAuthorize("@ps.any(@pay.monthlyWage.edit)")
    @Log(title = "月工资", businessType = BusinessType.UPDATE)
    @PutMapping
    public  Result edit(@Validated @RequestBody MonthlyWage entity){
        return super.edit(entity);
    }
    
    @ApiOperation("导出")
    @PreAuthorize("@ps.any(@pay.monthlyWage.export)")
    @Log(title = "月工资", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(MonthlyWage entity, PageDomain pageRequest,HttpServletResponse response)
    {
        var list=queryHelper.query().queryable(emsql,EmployeeMonthlyWageDto.class)
                .whereObject(entity)
                .where(entity.getTime() != null,
                        p -> p.rangeClosed(EmployeeMonthlyWageDto::getTime, DateUtil.beginOfMonth(entity.getTime()), DateUtil.endOfMonth(entity.getTime())))
                .orderBy(p -> p.column(EmployeeMonthlyWageDto::getOrderNum), true)
                .toList();
        pageRequest.setPageNum(1);
        pageRequest.setPageSize(Integer.MAX_VALUE);
        //var list = queryPage(entity,pageRequest).getRows();
        var util = new ExcelUtil<>(EmployeeMonthlyWageDto.class);
        util.exportExcel(response, list, "数据记录_"+DateUtil.today());
        //super.export(entity,pageRequest,null,response);
    }
    String emsql="select  a.*,b.bank_card,b.resign_time from pay_monthly_wage a left join pay_employee b  on a.user_id=b.user_id";
    @Resource
     WageSvc wageSvc;
     @ApiOperation("月工资单生成")
     @PreAuthorize("@ps.any(@pay.monthlyWage.add)")
     @Log(title = "月工资", businessType = BusinessType.INSERT)
     @PostMapping("/createMonthlyBill")
     public Result createMonthlyBill(){
         wageSvc.createMonthlyBill(new Date());
         return Result.ok();
     }
     @ApiOperation(value = "重新生成月工资单",notes = "参数示例： {time:'2025-01-09 00:00:01'}")
     @PreAuthorize("@ps.any(@pay.monthlyWage.reset)")
     @Log(title = "月工资", businessType = BusinessType.INSERT)
     @PostMapping("/resetMonthlyBill")
     public Result resetMonthlyBill(@RequestBody MonthlyWage dto) {
         var time=dto.getTime();
         var timeFmt = DateUtils.parseDateToStr("YYYYMM", time);
         var record = queryHelper.entityQuery(RunDataRecord.class)
                 .where(p -> p.runType().eq(RunDataRecord.MonthlyBillReset))
                 .where(p -> p.name().eq(timeFmt))
                 .firstOrNull();

         if (record!=null) {
             return Result.bad("只能重新生成一次月工资");
         }
         wageSvc.resetMonthlyBill(time);
         return Result.ok();
     }
     @ApiOperation("月工资其他信息修改")
     @PreAuthorize("@ps.any(@pay.monthlyWage.edit)")
     @Log(title = "月工资", businessType = BusinessType.UPDATE)
     @PostMapping("/editMonthlyBill")
     public Result editMonthlyBill(@RequestBody MonthlyWage[] monthlyWage){
         return wageSvc.editMonthlyBill(Arrays.asList(monthlyWage));
     }


     @Resource
 SalaryMapper salaryMapper;
     @PreAuthorize("@ps.any(@pay.monthlyWage.list)")
     @GetMapping("query")
     public Result  query( PageSort pageRequest) {
         var map=new HashMap<String,Object>();
         map.put("name",pageRequest.getOrderByName());
         var data= salaryMapper.query(map);
         return Result.ok(data);
     }
}